home *** CD-ROM | disk | FTP | other *** search
- Path: news.ichange.com!newsmaster
- From: Jesse Liberty <jl@staff.ichange.com>
- Newsgroups: comp.lang.c++
- Subject: Re: Help! Newbie question ...
- Date: Tue, 19 Mar 1996 07:49:08 -0500
- Organization: AT&T
- Message-ID: <314EAD44.B20@staff.ichange.com>
- References: <4ilkfu$41q@Kaos.deepcove.com>
- NNTP-Posting-Host: 140.244.99.60
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (Win95; I)
- CC: jl@staff.ichange.com
-
- Sean Affleck wrote:
- >
- > Is this legal ?
- >
- > class A {...};
- >
- > A f();
- >
- > main() {
- > A a = f();
- > }
- >
- > A f()
- > {
- > A fa;
- > return fa;
- > }
- >
-
- You CAN do this but you almost certainly don't want to. You are creating a local A object in your f() function and returning
- it by value. That means a copy of the A object is being created on the stack which is very inefficient. You'll almost
- certainly want to return by reference, but then you have a far bigger problem. You certainly don't want to return a reference
- to fa because it will go out of scope and be destroyed at the end of your function call.
-
- The right answer, as you suspected is to change fa to be a pointer to A and to allocate space on the heap and return the
- pointer. This gives you efficiency and safety but raises a design question: why is A allocating an objec to be used
- elsewhere? It usually makes sense to allocate the object in whatever function is going to then own it. There are exceptions,
- but you'd have to ask yourself why you're doing it this way.
-
- -j
-
- ------
- Jesse Liberty [AT&T New Media Services]
- jl@staff.ichange.com ZDNet: 72241,72
- Teach Yourself C++ In 21 Days. Sams 1994
- Teach Yourself MORE C++ In 21 Days. Sams 1996
- Teach Yourself ANSI C++ In 21 Days. Sams 1996
- C++: An Introduction To Programming. Que 1996
-